from flask import Blueprint, render_template, redirect, url_for, flash, request, current_app, send_file
from flask_login import login_required, current_user
from inc.models import BackupLog
from datetime import datetime, timedelta
from admin.admin.admin_backup import BackupManager

import os

admin_backup_bp = Blueprint('admin_backup', __name__)

@admin_backup_bp.route('/backup/perform', methods=['POST'])
@login_required

def perform_backup():
    backup_manager = BackupManager(current_app._get_current_object())
    success, message = backup_manager.perform_backup(
        operator_id=current_user.id,
        backup_type="manual"
    )
    if success:
        flash(message, 'success')
    else:
        flash(message, 'danger')
    return redirect(url_for('admin.admin_config.database_config'))

@admin_backup_bp.route('/backup/list')
@login_required

def list_backups():
    try:
        backup_manager = BackupManager(current_app._get_current_object())
        backups = backup_manager.list_backups()
        backup_logs = BackupLog.query.all()
        status_dict = {log.filename: log.status for log in backup_logs}

        # 确保每个备份对象都有status属性
        for backup in backups:
            backup['status'] = status_dict.get(backup['filename'], 'unknown')

        return render_template('admin/admin/admin_backups.html',
                             backups=backups,
                             active_page='backup')
    except Exception as e:
        current_app.logger.error(f"获取备份列表失败: {str(e)}")
        return render_template('admin/admin/admin_backups.html',
                             backups=[],
                             active_page='backup')

@admin_backup_bp.route('/backup-logs')
@login_required

def backup_logs():
    page = request.args.get('page', 1, type=int)
    per_page = 20
    logs = BackupLog.query.order_by(BackupLog.backup_time.desc()).paginate(page=page, per_page=per_page)
    return render_template('admin/admin/admin_backlog.html', logs=logs)

@admin_backup_bp.route('/backup/download/<filename>')
@login_required

def download_backup(filename):
    backup_manager = BackupManager(current_app._get_current_object())
    backup_path = os.path.join(backup_manager._get_backup_dir(), filename)
    if not os.path.exists(backup_path):
        flash('备份文件不存在', 'danger')
        return redirect(url_for('admin.admin_backup.list_backups'))
    return send_file(
        backup_path,
        as_attachment=True,
        download_name=filename
    )

@admin_backup_bp.route('/backup/delete/<filename>', methods=['POST'])
@login_required

def delete_backup(filename):
    backup_manager = BackupManager(current_app._get_current_object())
    backup_path = os.path.join(backup_manager._get_backup_dir(), filename)
    if not os.path.exists(backup_path):
        flash('备份文件不存在', 'danger')
        return redirect(url_for('admin.admin_backup.list_backups'))
    try:
        os.remove(backup_path)
        flash(f'已删除备份: {filename}', 'success')
    except Exception as e:
        flash(f'删除备份失败: {str(e)}', 'danger')
    return redirect(url_for('admin.admin_backup.list_backups'))

@admin_backup_bp.route('/backup/restore', methods=['POST'])
@login_required

def restore_backup():
    backup_file = request.form.get('backup_file')
    if not backup_file:
        flash('请选择要恢复的备份文件', 'danger')
        return redirect(url_for('admin.admin_backup.list_backups'))
    confirmation = request.form.get('confirmation')
    if confirmation != 'YES':
        flash('恢复操作需要确认，请在确认框中输入"YES"', 'danger')
        return redirect(url_for('admin.admin_backup.list_backups'))
    backup_manager = BackupManager(current_app._get_current_object())
    success, message = backup_manager.perform_restore(
        backup_file=backup_file,
        operator_id=current_user.id
    )
    if success:
        flash(message, 'success')
        try:
            from inc.config_manager import SystemConfigManager
            SystemConfigManager.get_config(refresh=True)
            flash('配置已重新加载', 'success')
        except Exception as e:
            flash(f'重新加载配置失败: {str(e)}', 'warning')
    else:
        flash(message, 'danger')
    return redirect(url_for('admin.admin_backup.list_backups'))